(function() {
   
let Cc = Components.classes, Ci = Components.interfaces;
let prefService = Cc['@mozilla.org/preferences-service;1'].getService(Ci.nsIPrefService);
let prefBranch = prefService.getBranch('extensions.stratabuddy.').QueryInterface(Ci.nsIPrefBranch2);
let prefGeneral = prefService.QueryInterface(Ci.nsIPrefBranch2);
let ssService = Cc['@mozilla.org/content/style-sheet-service;1'].getService(Ci.nsIStyleSheetService);
let ioService = Cc['@mozilla.org/network/io-service;1'].getService(Ci.nsIIOService);

const BaseURI = ioService.newURI('chrome://StrataBuddy/skin/css/', null, null);

function enableStyleSheet(sheet) {
  if (!ssService.sheetRegistered(sheet, ssService.USER_SHEET))
    ssService.loadAndRegisterSheet(sheet, ssService.USER_SHEET);
}

function disableStyleSheet(sheet) {
  if (ssService.sheetRegistered(sheet, ssService.USER_SHEET))
    ssService.unregisterSheet(sheet, ssService.USER_SHEET);
}

function loadStyleSheet(url, base) {
  var sheet = ioService.newURI(url, null, base);
  enableStyleSheet(sheet);
  return sheet;
}

const Dwm = {

  _dwm: null,
  _tabBox: null,
  _toolBox: null,
  _tabpanelsBox: null,
  _bottomBox: null,
  _ss: null,

  onGlassChange: {
    handleEvent: function(evt) {
      if (Dwm._dwm.GlassEnabled) {
        enableStyleSheet(Dwm._ss);
        gBrowser.addEventListener('resize', Dwm.onWindowResized, false);
        Dwm.onWindowResized.handleEvent();
      } else {    
        disableStyleSheet(Dwm._ss);
        gBrowser.removeEventListener('resize', Dwm.onWindowResized, false);
      }
    }
  },

  onWindowResized: {
    disabled: false,
    handleEvent: function(evt) {
      if (window.fullScreen) {
        if (!this.disabled) {
          disableStyleSheet(Dwm._ss);
          Dwm._dwm.ExtendFrameIntoWindow(0, 0, 0, 0);
          this.disabled = true;
        }
      } else {
        enableStyleSheet(Dwm._ss);
        var top = Dwm._tabpanelsBox.y;
        if (Dwm._tabBox.y < 0) top += Dwm._tabBox.height + Dwm._tabBox.y;
        var padding = window.windowState == STATE_MAXIMIZED ? 0 : 2;
        Dwm._dwm.ExtendFrameIntoWindow(top + 2, padding, Dwm._bottomBox.height + padding, padding);
        this.disabled = false;
      }
    }
  },

  enable: function(ss) {
    if (!this._dwm) {
      this._dwm = Cc['@sixxgate.com/DwmCalls/CDwmCalls;1'].createInstance().QueryInterface(Ci.IDwmCalls);
      var baseWindow = window.QueryInterface(Ci.nsIInterfaceRequestor)
                             .getInterface(Ci.nsIWebNavigation)
                             .QueryInterface(Ci.nsIDocShellTreeItem)
                             .treeOwner
                             .QueryInterface(Ci.nsIInterfaceRequestor)
                             .getInterface(Ci.nsIXULWindow)
                             .docShell
                             .QueryInterface(Ci.nsIBaseWindow);
      this._dwm.AttachToWindow(baseWindow);
      this._tabBox = gBrowser.mTabContainer.boxObject;
      this._toolBox = window.document.getElementById('navigator-toolbox').boxObject;
      this._bottomBox = window.document.getElementById('browser-bottombox').boxObject;
      this._tabpanelsBox = gBrowser.mTabBox._tabpanels.boxObject;
    }
    this._ss = ss;
    this._dwm.OnGlassChange = this.onGlassChange;
    this.onGlassChange.handleEvent();
  },

  disable: function() {
    this._dwm.OnGlassChange = null;
    gBrowser.removeEventListener('resize', this.onWindowResized, false);
    this.onWindowResized.disable = false;
    this._dwm.ExtendFrameIntoWindow(0, 0, 0, 0);
    this._ss = null;
  }

};

const StaticPrefs = {
  prefs: {
    'appbutton': {
      1: {
        css: 'FirefoxAppbuttonStyle2.css'
      },
      2: {
        css: 'FirefoxAppbuttonStyle3.css'
      },
      3: {
        css: 'FirefoxAppbuttonStyle5.css'
      },
      4: {
        css: 'FirefoxAppbuttonStyle4.css'
      },
      5: {
        css: 'FirefoxAppbuttonStyle6.css'
      },
      6: {
        css: 'FirefoxAppbuttonStyle7.css'
      },
      7: {
        css: 'FirefoxAppbuttonStyle8.css'
      },
      8: {
        css: 'FirefoxAppbuttonStyle9.css'
      }
    },  
     'glass': {
      true: {
        css: 'Glass.css',
        binding: Dwm
      }
    },
         'hidenewtab': {
      true: {
        css: 'HideNewTab.css',
      }
    },
          'hidealltab': {
      true: {
        css: 'HideAllTabs.css',
      }
    },
             'hideappbutton': {
      true: {
        css: 'HideAppButton.css',
      }
    },
              'alwaysclosetab': {
      true: {
        css: 'AlwaysCloseTab.css',
      }
    },
               'showhometab': {
      true: {
        css: 'ShowHomeTab.css',
      }
    },
               'hidehistory': {
      true: {
        css: 'HideHistory.css',
      }
    },
             'showdev': {
      true: {
        css: 'ShowDev.css',
      }
    },
    'tabstyle': {
      1: {
        css: '37TabBG.css'
      },
       2: {
        css: 'TabsOnTop.css'
      }
    },
  },

  getPrefValue: function(key) {
    switch (prefBranch.getPrefType(key)) {
      case prefBranch.PREF_INT:
        return prefBranch.getIntPref(key);
      case prefBranch.PREF_BOOL:
        return prefBranch.getBoolPref(key);
    }
    return null;
  },

  enableNew: function(pref, val) {
    pref.last = val;
    if (!(val in pref))
      return;
    var valOpt = pref[val];
    if ('css' in valOpt)
      pref.ref = loadStyleSheet(valOpt.css, BaseURI);
    if ('binding' in valOpt)
      valOpt.binding.enable(pref.ref);
  },

  disableLast: function(pref) {
    if (pref.last == undefined || !(pref.last in pref))
      return;
    if (pref.ref) {
      disableStyleSheet(pref.ref);
      pref.ref = null;
    }
    if ('binding' in pref[pref.last])
      pref[pref.last].binding.disable();
  },

  onPrefChange : {
    observe: function(subject, topic, key) {
      if (topic != 'nsPref:changed' || !(key in StaticPrefs.prefs))
        return;
      var pref = StaticPrefs.prefs[key];
      var val = StaticPrefs.getPrefValue(key);
      if (pref.last == val)
        return;
      StaticPrefs.disableLast(pref);
      if (val != null)
        StaticPrefs.enableNew(pref, val);
    }
  },

  enable: function() {
    for (var key in this.prefs) {
      var val = this.getPrefValue(key);
      if (val != null)
        this.enableNew(this.prefs[key], val);
    }
    prefBranch.addObserver('', this.onPrefChange, false);
  },

  disable: function() {
    for (var key in this.prefs)
      this.disableLast(this.prefs[key]);
    prefBranch.removeObserver('', this.onPrefChange);
  }

};

function init() {
  window.removeEventListener('load', init, false);
  StaticPrefs.enable();
 // if (navigator.oscpu.match('NT 5'))
//    loadStyleSheet('css/xpfixes.css', BaseURI);
  if (Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo).version.indexOf('3.7') == 0)
    loadStyleSheet('css/37piethrobber.css', BaseURI);
  if (Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo).version.indexOf('3.5') == 0)
    loadStyleSheet('css/35fixes.css', BaseURI);
  if (prefGeneral.getCharPref('extensions.enabledItems').indexOf('undoclosedtabsbutton@supernova00.biz') > -1)
     loadStyleSheet('undoclosedtab.css', BaseURI);
}

function term() {
  window.removeEventListener('unload', term, false);
  StaticPrefs.disable();
}

window.StrataBuddy = {
  restart: function(evt) {
    var os = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
    var cancelQuit = Cc['@mozilla.org/supports-PRBool;1'].createInstance(Ci.nsISupportsPRBool);
    os.notifyObservers(cancelQuit, 'quit-application-requested', 'restart');
    if (cancelQuit.data) return;
    var restart = Cc['@mozilla.org/toolkit/app-startup;1'].getService(Ci.nsIAppStartup);
    restart.quit(restart.eRestart | restart.eAttemptQuit).focus();
  },
  openProfD: function(evt) {
    var directoryService = Cc['@mozilla.org/file/directory_service;1'].getService(Ci.nsIProperties);
    var profileFolder = directoryService.get('ProfD', Ci.nsIFile);
    var fileLocal = Cc['@mozilla.org/file/local;1'].getService(Ci.nsILocalFile);
    fileLocal.initWithPath(profileFolder.QueryInterface(Ci.nsILocalFile).path);
    fileLocal.launch();
  },
  setMainMenu: function(evt) {
	var pbs = Components.classes["@mozilla.org/privatebrowsing;1"]  
                    .getService(Components.interfaces.nsIPrivateBrowsingService);  
    var inPrivateBrowsingMode = pbs.privateBrowsingEnabled;
	var ptoolbar = window.document.getElementById("PersonalToolbar");
	var mtoolbar = window.document.getElementById("toolbar-menubar"); 
	  window.document.getElementById('ttb_private_cb').setAttribute('checked', inPrivateBrowsingMode);
      window.document.getElementById('ttb_personal_cb').setAttribute('checked', ptoolbar.getAttribute("collapsed") != "true");
	  window.document.getElementById('ttb_menu_cb').setAttribute('checked', mtoolbar.getAttribute("autohide") != "true");
	  },
  onMenuCommandToggle: function(evt) {
    var el = evt.target;
    var toolbar = window.document.getElementById(el.value);
	if (el.value == 'PersonalToolbar') {
	toolbar.setAttribute('collapsed', !el.hasAttribute('checked'));
	window.document.persist(el.value, 'collapsed');
	}
	else if (el.value == 'toolbar-menubar'){
	toolbar.setAttribute('autohide', !el.hasAttribute('checked'));
	window.document.persist(el.value, 'autohide');
	}
  },
  setBookmarksMenu: function(evt) {
    let hid1 = prefBranch.getBoolPref('hidebookthispage'), hid2 = prefBranch.getBoolPref('hideorganize');
    window.document.getElementById('redux_addbookmark').style.display = hid1 ? 'none' : '';
    window.document.getElementById('redux_organizebookmark').style.display = hid2 ? 'none' : '';
    window.document.getElementById('redux_bk_sep').style.display = hid1 && hid2 ? 'none' : '';
  }
};

window.addEventListener('load', init, false);
//window.addEventListener('unload', term, false);
})();